package com.example.nio.netty.server;

import com.example.nio.netty.protoco.request.LoginRequest;
import com.example.nio.netty.protoco.response.LoginResponse;
import com.example.nio.netty.session.Session;
import com.example.nio.netty.session.SessionUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.util.Date;
import java.util.UUID;

@Sharable
public class EchoServerHandler extends SimpleChannelInboundHandler<LoginRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequest msg) throws Exception {
        System.out.println(new Date()+"登陆用户："+msg.toString());
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setResult(true);
        loginResponse.setUserId(UUID.randomUUID().toString().split("-")[0]);

        Session session = new Session(loginResponse.getUserId(), msg.getUserName());
        System.out.println(msg.toString());
        SessionUtil.bindSession(ctx.channel(),session);

        ctx.channel().writeAndFlush(loginResponse);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
        Throwable cause) {
        cause.printStackTrace();//打印异常栈跟踪
        ctx.close();//关闭该Channel
    } @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("客户端连接被关闭!");
    }
}
